﻿#include "HNHomeScence.h"
#include "Game/GameLib.h"
#include "JniCross/JniFun.h"
#include "Games/NiuNiu/JDNNSoundFun.h"
#include "HNLogonScence.h"

#include "Main/configConst.h";

FV_SINGLETON_STORAGE(HNHomeScence);

HNHomeScence::HNHomeScence()
{
	init();
	CServerListData::shared()->SetServerListDataSink(this);
	UserInfo::Instance().addUpPlayerInfoCB(this, QY_CALLFUNC_SELECTOR(HNHomeScence::upPlayerInfo));
	UserInfo::Instance().addLoginSucessCB(this, QY_CALLFUNC_SELECTOR(HNHomeScence::LogonSucess));
}
HNHomeScence::~HNHomeScence() 
{

}
bool HNHomeScence::init()
{
	if (!Node::init())
	{
		return false;
	};

	//m_localUserId = 0;
	
	_layout = CSLoader::createNode("homeSceneLayer.csb");
	addChild(_layout);
	initButtonTouchEvent();

	auto m_MusicValue = cocos2d::UserDefault::getInstance()->getIntegerForKey("NEW_MUSIC_VALUE", 100);
	auto m_EffectValue = cocos2d::UserDefault::getInstance()->getIntegerForKey("NEW_EFFECT_VALUE", 100);
	CGlobalUserInfo::GetInstance()->setMusicValue(m_MusicValue);
	CGlobalUserInfo::GetInstance()->setEffectValue(m_EffectValue);
	SimpleAudioEngine::getInstance()->setEffectsVolume((float)m_EffectValue / 100.0);
	SimpleAudioEngine::getInstance()->setBackgroundMusicVolume((float)m_MusicValue / 100.0);


	initHelpLayer();
	initYeJiLayer();

	return true;
}

void HNHomeScence::initButtonTouchEvent()
{
	const std::string homeButtons[11] = { "Button_head", "Button_add", "Button_create", "Button_join", "Button_setting", "Button_kefu", "Button_shop", "Button_notice", "Button_share", "Button_help","Button_yeji" };

	for (int i = 0; i < 11; i++)
	{
		auto btn = (Button*)_layout->getChildByName(homeButtons[i]);
		btn->addTouchEventListener(CC_CALLBACK_2(HNHomeScence::BtnCallBack, this));
		if (i == 2)
			btn_create = btn; 
	}
}

void HNHomeScence::EnterScence()
{
	JDNNSoundFun::stopBackMusic();
	SoundFun::playBackMusic("backMusic.mp3");

	if (CGlobalUserInfo::GetInstance()->isBackRoom)
	{
	btn_create->loadTextureNormal("lobby2/ui_zyxiugai_bth1.png");
	}
	else
	{
	btn_create->loadTextureNormal("lobby2/ui_zyxiugai_bth3.png");
	}

	TextAtlas* userZhanshi = (TextAtlas*)_layout->getChildByName("AtlasLabel_zhuanshi");
	userZhanshi->setString(StringUtils::format("%lld", CGlobalUserInfo::GetInstance()->getUserDomain()));

	//int  m_wServerIDi = CGlobalUserInfo::GetInstance()->GetUserInsureInfo()->wServerID;
	//CCLOG("###################  ==  %d", m_wServerIDi);

	auto m_MusicValue = cocos2d::UserDefault::getInstance()->getIntegerForKey("NEW_MUSIC_VALUE", 100);
	auto m_EffectValue = cocos2d::UserDefault::getInstance()->getIntegerForKey("NEW_EFFECT_VALUE", 100);
	CGlobalUserInfo::GetInstance()->setMusicValue(m_MusicValue);
	CGlobalUserInfo::GetInstance()->setEffectValue(m_EffectValue);
	SimpleAudioEngine::getInstance()->setEffectsVolume((float)m_EffectValue / 100.0);
	SimpleAudioEngine::getInstance()->setBackgroundMusicVolume((float)m_MusicValue / 100.0);
	
	//m_localUserId = CGlobalUserInfo::GetInstance()->getUserID();
}
void HNHomeScence::upPlayerInfo()
{
	utility::log("SCHomeScence::upPlayerInfo()"); 

	Text* nickName = (Text*)_layout->getChildByName("Text_nickName");
	nickName->setString(UserInfo::Instance().getUserNicName());


	Text* userId = (Text*)_layout->getChildByName("Text_nickID");
	userId->setString(StringUtils::format(utility::getScriptString("word_userInfo_id").c_str(), UserInfo::Instance().getUserID()));

	Text* userZhanshi = (Text*)_layout->getChildByName("Text_zhuanshi");
	userZhanshi->setString(StringUtils::format("%lld", UserInfo::Instance().getUserDomain()));

	Sprite* headImage = (Sprite*)_layout->getChildByName("head_image");

	if (!UserInfo::Instance().getHeadHttp().empty())
	{
		ImagicDownManager::Instance().addDown(headImage,
			UserInfo::Instance().getHeadHttp(), UserInfo::Instance().getUserID());
	}
	else
	{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
		if (UserInfo::Instance().getGender() == 0)
			headImage->setTexture("common/head3.png");
		else
			headImage->setTexture("common/head3.png");
#endif		
	}
}
void HNHomeScence::LogonSucess() 
{
	if (!HNLogonScence::Instance().m_kWeiXinUserInfo.headimgurl.empty() && !HNLogonScence::Instance().m_kWeiXinUserInfo.nickname.empty())
	{
		/*std::string updateHeadUrl = StringUtils::format("http://dl.rdaohy.com:8888/app/face/upt?uid=%d&face=%s", UserInfo::Instance().getUserID(), HNLogonScence::Instance().m_kWeiXinUserInfo.headimgurl.c_str());
		MCWebReq::instance().sendRequestDocumentUrl(updateHeadUrl, nullptr, CC_CALLBACK_1(HNHomeScence::Rsp_uptHeadUrl_list, this));*/

		std::string updateHeadUrl = StringUtils::format("%s/AvatarInterface.aspx?type=modify&id=%d&faceImg=%s&nickname=%s", bzyfk_url.c_str(), UserInfo::Instance().getUserID(), HNLogonScence::Instance().m_kWeiXinUserInfo.headimgurl.c_str(),
			HNLogonScence::Instance().m_kWeiXinUserInfo.nickname.c_str());
		MCWebReq::instance().sendRequestDocumentUrl(updateHeadUrl, nullptr, CC_CALLBACK_1(HNHomeScence::Rsp_uptHeadUrl_list, this));

		log("user head url:%s", HNLogonScence::Instance().m_kWeiXinUserInfo.headimgurl.c_str());
		log("user nickName url:%s", HNLogonScence::Instance().m_kWeiXinUserInfo.nickname.c_str());
	}
	UserInfo::Instance().reqAccountInfo();


}

void HNHomeScence::Rsp_shop_list(const std::string& data)
{
	rapidjson::Document doc;
	doc.Parse<rapidjson::kParseDefaultFlags>(data.c_str());
	if (doc.HasParseError() || !doc.IsArray())
	{
		return;
	}
	UserDefault::getInstance()->setStringForKey("JDNN_SHOP_LIST",data);
	UserDefault::getInstance()->flush();
}

void HNHomeScence::Rsp_news_list(const std::string& data)
{
	rapidjson::Document doc;
	doc.Parse<rapidjson::kParseDefaultFlags>(data.c_str());
	if (doc.HasParseError() || !doc.IsArray())
	{
		return;
	}
	for (auto i = 0; i < doc.Size(); i++)
	{
		if (!doc[i].IsObject() || !doc[i].HasMember("subject"))
		{
			continue;
		}
		std::string subject = doc[i]["subject"].GetString();
		Text* textNoti = (Text*)_layout->getChildByName("Text_noticeMsg");
		textNoti->setString(subject);
	}
}

void HNHomeScence::Rsp_notice_list(const std::string& data)
{
	rapidjson::Document doc;
	doc.Parse<rapidjson::kParseDefaultFlags>(data.c_str());
	if (doc.HasParseError() || !doc.IsArray())
	{
		return;
	}
	for (auto i = 0; i < doc.Size(); i++)
	{
		if (!doc[i].IsObject() || !doc[i].HasMember("subject"))
		{
			continue;
		}
		std::string subject = doc[i]["subject"].GetString();
		_Notic->postMessage(subject,0);
	}
}

void HNHomeScence::Rsp_uptHeadUrl_list(const std::string& data)
{
	rapidjson::Document doc;
	doc.Parse<rapidjson::kParseDefaultFlags>(data.c_str());
	if (doc.HasParseError() || !doc.IsArray())
	{
		return;
	}
}

void HNHomeScence::Rsp_kefu_list(const std::string& data)
{
	rapidjson::Document doc;
	doc.Parse<rapidjson::kParseDefaultFlags>(data.c_str());
	if (doc.HasParseError() || !doc.IsArray())
	{
		return;
	}
	UserDefault::getInstance()->setStringForKey("JDNN_KEFU_LIST", data);
	UserDefault::getInstance()->flush();
}

void HNHomeScence::Rsp_yeji_list(const std::string& data)
{
	rapidjson::Document doc;
	doc.Parse<rapidjson::kParseDefaultFlags>(data.c_str());

	if (doc.HasParseError() || !doc.HasMember("msg"))
	{
		return;
	}

	std::string msg = doc["msg"].GetString();

	if (msg == "500")
	{
		CCLOG(" no record !!!");
		txt_error->setString(utility::getScriptString("TuiGuangError_1"));
		return;
	}
	if (msg == "404")
	{
		CCLOG(" no tuiGuangYuan !!!");
		txt_error->setString(utility::getScriptString("TuiGuangError_2"));
		return;
	}

	if (doc.HasParseError() || !doc.HasMember("List") || !doc["List"].IsArray() || !doc.HasMember("msg"))
	{
		return;
	}

	for (auto i = 0; i < doc["List"].Size(); i++)
	{
		YeJiRecord mRecord;
		mRecord.nickName = doc["List"][i]["NickName"].GetString();
		mRecord.money1 = doc["List"][i]["PayMoney"].GetString();
		mRecord.time = doc["List"][i]["AddTime"].GetString();
		mRecord.money2 = doc["List"][i]["InComeMoney"].GetString();
		vecYeJiRecord.push_back(mRecord);
	}

	m_AllMoney1 = doc["Recharge"].GetString();
	m_AllMoney2 = doc["Income"].GetString();

}


void HNHomeScence::initHelpLayer()
{
	_helpLayout = CSLoader::createNode("GameHelpLayer.csb");
	addChild(_helpLayout);
	hideHelpLayer();

	auto btn = (Button*)_helpLayout->getChildByName("Button_close");
	btn->addTouchEventListener(CC_CALLBACK_2(HNHomeScence::BtnCallBack, this));
	btn = (Button*)_helpLayout->getChildByName("Button_NiuNiu");
	btn->addTouchEventListener(CC_CALLBACK_2(HNHomeScence::BtnCallBack, this));
	btnGame[0] = btn;
	btn = (Button*)_helpLayout->getChildByName("Button_BaiJiaLe");
	btn->addTouchEventListener(CC_CALLBACK_2(HNHomeScence::BtnCallBack, this));
	btnGame[1] = btn;
	btn = (Button*)_helpLayout->getChildByName("Button_MaJiang");
	btn->addTouchEventListener(CC_CALLBACK_2(HNHomeScence::BtnCallBack, this));
	btnGame[2] = btn;
	btnGame[2]->setVisible(false);

	panelGame[0] = (Layout*)_helpLayout->getChildByName("Panel_NiuNiu");
	panelGame[1] = (Layout*)_helpLayout->getChildByName("Panel_BaiJiaLe");
	panelGame[2] = (Layout*)_helpLayout->getChildByName("Panel_MaJiang");
}
void HNHomeScence::showHelpLayer()
{
	_helpLayout->setPosition(0, 0);
}
void HNHomeScence::hideHelpLayer()
{
	_helpLayout->setPosition(0, 1100);
}


void HNHomeScence::initYeJiLayer()
{
	_yejiLayout = CSLoader::createNode("YeJiLayer.csb");
	addChild(_yejiLayout);
	hideYeJiLayer();

	auto btn = (Button*)_yejiLayout->getChildByName("Button_close2");
	btn->addTouchEventListener(CC_CALLBACK_2(HNHomeScence::BtnCallBack, this));

	btnMonth[0] = (Button*)_yejiLayout->getChildByName("Button_1");
	btnMonth[0]->addTouchEventListener(CC_CALLBACK_2(HNHomeScence::BtnCallBack2, this));
	btnMonth[1] = (Button*)_yejiLayout->getChildByName("Button_2");
	btnMonth[1]->addTouchEventListener(CC_CALLBACK_2(HNHomeScence::BtnCallBack2, this));
	btnMonth[2] = (Button*)_yejiLayout->getChildByName("Button_3");
	btnMonth[2]->addTouchEventListener(CC_CALLBACK_2(HNHomeScence::BtnCallBack2, this));

	_listView = (ListView*)_yejiLayout->getChildByName("ListView_1");
	txt_error = (Text*)_yejiLayout->getChildByName("Text_error");

	txt_allMoney1 = (Text*)_yejiLayout->getChildByName("Text_allMoney1");
	txt_allMoney1->setString("");
	txt_allMoney2 = (Text*)_yejiLayout->getChildByName("Text_allMoney2");
	txt_allMoney2->setString("");

	getDateTime();
	if (m_Month == 1)
	{
		month[2] = 1;
		month[1] = 12;
		month[0] = 11;
	}
	else if (m_Month == 2)
	{
		month[2] = 2;
		month[1] = 1;
		month[0] = 12;
	}
	else
	{
		month[2] = m_Month;
		month[1] = m_Month - 1;
		month[0] = m_Month - 2;
	}
	auto txt = (Text*)btnMonth[0]->getChildByName("Text_1");
	txt->setString(utility::getScriptString(StringUtils::format("Month_%d", month[0])));
	txt = (Text*)btnMonth[1]->getChildByName("Text_1");
	txt->setString(utility::getScriptString(StringUtils::format("Month_%d", month[1])));
	txt = (Text*)btnMonth[2]->getChildByName("Text_1");
	txt->setString(utility::getScriptString(StringUtils::format("Month_%d", month[2])));

	clearYeJiRecord();
	
}

void HNHomeScence::showYeJiLayer()
{
	_yejiLayout->setPosition(0, 0);
}

void HNHomeScence::hideYeJiLayer()
{
	_yejiLayout->setPosition(0, 1100);
}


void HNHomeScence::createYeJiRecord(const std::string nickName, const std::string money1, const std::string time, const std::string money2)
{
	auto layout = Layout::create();
	layout->setContentSize(Size(1240,60));

	Text* txtNickName = Text::create(nickName, "common/WRYH.ttf", 30);
	txtNickName->setPosition(Vec2(140, 30));
	layout->addChild(txtNickName);

	Text* txtMoney1 = Text::create(money1, "common/WRYH.ttf", 30);
	txtMoney1->setPosition(Vec2(460, 30));
	layout->addChild(txtMoney1);

	Text* txtTime = Text::create(time, "common/WRYH.ttf", 30);
	txtTime->setPosition(Vec2(780, 30));
	layout->addChild(txtTime);

	Text* txtMoney2 = Text::create(money2, "common/WRYH.ttf", 30);
	txtMoney2->setPosition(Vec2(1100, 30));
	layout->addChild(txtMoney2);

	_listView->pushBackCustomItem(layout);
}

void HNHomeScence::clearYeJiRecord()
{
	m_AllMoney1 = "";
	m_AllMoney2 = "";
	txt_error->setString("");
	vecYeJiRecord.clear();
	_listView->removeAllChildrenWithCleanup(true);
}

void HNHomeScence::queryYeJiRecord(const int userId, const std::string month)
{
	//UserInfo::Instance().getUserID()
	std::string yejiUrl = StringUtils::format("%s/admin/ProxyPromotionRewardInterface.aspx?AgentId=%d&dateTime=%s", bzyfk_url.c_str(), userId, month.c_str());
	MCWebReq::instance().sendRequestDocumentUrl(yejiUrl, nullptr, CC_CALLBACK_1(HNHomeScence::Rsp_yeji_list, this));
}


void HNHomeScence::getDateTime()
{
	struct tm *tm;
	time_t timep;
	time(&timep);
	tm = localtime(&timep);
	m_Year = tm->tm_year + 1900;
	m_Month = tm->tm_mon+1;
	CCLOG("Year = %d, Month = %d", m_Year, m_Month);
}